package com.borrow.jiemihua.update;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseApplication;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.FileCallback;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;


/**
 * Created by yzy on 2016/5/20.
 */
public class DownLoadService extends Service {
    private Context mContext = this;
    // notification 名字
    String notify_name = "正在下载...";
    Notification mNotification;
    private static final int NOTIFY_ID = 0;
    private NotificationManager mNotificationManager;
    /* 下载包安装路径 */
    private static final String saveFileName = "/sdcard/借米花日志";
    private String apkUrl;
    private int progress;
    boolean canceled;
    Thread downLoadThread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent.hasExtra("url")) {
            apkUrl = intent.getStringExtra("url");
        }
        if (isStart) {
            progress = 0;
            setUpNotification();
            new Thread() {
                public void run() {
                    // 开始下载
                    startDownload();
                }
            }.start();
        } else {
            Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "应用下载中", Toast.LENGTH_LONG).show();
        }
        return startId;
    }

    private void startDownload() {
        canceled = false;
        downloadApk();
    }

    boolean isStart = true;
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    // 下载完毕
                    // 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    File file = (File) msg.obj;
                    Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "下载完毕", Toast.LENGTH_LONG).show();
                    isStart = true;
                    installApk(file);
                    break;
                case 2:
                    // 这里是用户界面手动取消，所以会经过activity的onDestroy();方法
                    // 取消通知
                    mNotificationManager.cancel(NOTIFY_ID);
                    break;
                case 1:
                    float rate = (float) msg.obj;
                    int pro = (int) (rate * 100);
                    if (isStart) {
                        Toast.makeText(BaseApplication.getInstance().getApplicationContext(), "开始下载...", Toast.LENGTH_LONG).show();
                        isStart = false;
                    }
                    if (rate < 1) {
                        Notification.Builder builder = new Notification.Builder(mContext)
                                .setAutoCancel(false)
                                .setSmallIcon(R.mipmap.logo)
                                .setTicker("开始下载")
                                .setContentTitle("应用下载中...")
                                .setWhen(System.currentTimeMillis())
                                //      .setDefaults(Notification.DEFAULT_ALL)
                                .setOngoing(true)
                                .setContentText(pro + "%")
                                .setProgress(100, pro, false);
                        contentView.setTextViewText(R.id.tv_progress, pro + "%");
                        contentView.setProgressBar(R.id.progress, 100, pro, false);
                        // 指定内容意图
//                        builder.setContent(contentView);
                        mNotification = builder.build();
                    } else {
                        // 下载完毕后变换通知形式
                        Notification.Builder builder = new Notification.Builder(mContext)
                                .setAutoCancel(false)
                                .setTicker("下载完成")
                                .setSmallIcon(R.mipmap.logo)
                                .setContentTitle("下载完成")
                                .setContentText("文件已下载完毕")
                                .setDefaults(Notification.FLAG_AUTO_CANCEL);

                        mNotification = builder.build();
                        stopSelf();// 停掉服务自身
                    }
                    PendingIntent contentIntent2 = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
                    mNotification.contentIntent = contentIntent2;
                    mNotificationManager.notify(NOTIFY_ID, mNotification);
                    break;
                case 3:
                    mNotification.flags = Notification.FLAG_AUTO_CANCEL;
                    Notification.Builder builder = new Notification.Builder(mContext)
                            .setAutoCancel(false)
                            .setSmallIcon(R.mipmap.logo)
                            .setTicker("借米花")
                            .setWhen(System.currentTimeMillis())
                            //      .setDefaults(Notification.DEFAULT_ALL)
                            .setOngoing(true)
                            .setContentText("下载失败！");
                    // 指定个性化视图
                    mNotification = builder.build();
                     /*   Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                        // 指定内容意图
                        mNotification.contentIntent = contentIntent;*/
                    mNotificationManager.notify(NOTIFY_ID, mNotification);

                    stopSelf();// 停掉服务自身
                    break;

            }
        }
    };

    /**
     * 安装apk
     *
     * @param file
     */
    private void installApk(File file) {
        Log.i("TAG", "file---------------" + file.toString());
        if (!file.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + file.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

    /**
     * 下载apk
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            OkHttpUtils.get(apkUrl)//
                    .tag(this)//
                    .execute(new FileCallback(saveFileName, "updateApp.apk") {  //文件下载时，可以指定下载的文件目录和文件名
                        @Override
                        public void onSuccess(File file, Call call, Response response) {
                            // file 即为文件数据，文件保存在指定目录
                            Message msg = mHandler.obtainMessage();
                            msg.what = 0;
                            msg.obj = file;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            Message msg = mHandler.obtainMessage();
                            msg.what = 3;
                            mHandler.sendMessage(msg);
                        }

                        @Override
                        public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                            //这里回调下载进度(该回调在主线程,可以直接更新ui)
                            //currentSize totalSize以字节byte为单位
                            // 更新进度
                            Message msg = mHandler.obtainMessage();
                            msg.what = 1;
                            msg.obj = progress;
                            mHandler.sendMessage(msg);
                        }
                    });
        }
    };
    RemoteViews contentView;

    /**
     * 创建通知
     */
    private void setUpNotification() {
        Notification.Builder builder = new Notification.Builder(mContext)
                .setAutoCancel(false)
                .setSmallIcon(R.mipmap.logo)
                .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.logo))
                .setTicker("开始下载")
                .setWhen(System.currentTimeMillis())
                //      .setDefaults(Notification.DEFAULT_ALL)
                .setOngoing(true);
        contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
        contentView.setTextViewText(R.id.tv_text, notify_name);
        contentView.setImageViewResource(R.id.image, R.mipmap.logo);
        // 指定个性化视图
        builder.setContent(contentView);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);

        // 指定内容意图
        builder.setContentIntent(contentIntent);

        mNotification = builder.getNotification();

        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }
}

